package com.xscha.tableforge.controller;

import com.xscha.tableforge.model.dto.RelationMetaDto;
import com.xscha.tableforge.model.entity.RelationMeta;
import com.xscha.tableforge.model.vo.RelationMetaVo;
import com.xscha.soyue.common.core.domain.R;
import com.xscha.tableforge.service.RelationMetaService;
import com.xscha.soyue.common.core.utils.BeanMapperUtils;
import com.xscha.tableforge.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 关联字段元数据控制器
 */
@RestController
@RequestMapping("/api/relation-fields")
public class RelationMetaController {

    private final RelationMetaService relationMetaService;

    @Autowired
    public RelationMetaController(RelationMetaService relationMetaService) {
        this.relationMetaService = relationMetaService;
    }

    /**
     * 根据ID查询关联字段元数据
     */
    @GetMapping("/{id}")
    public R<RelationMetaVo> getRelationFieldById(@PathVariable String id) {
        return relationMetaService.findById(id)
                .map(relation -> R.ok(BeanMapperUtils.map(relation, RelationMetaVo.class)))
                .orElse(R.fail("关联字段不存在"));
    }

    /**
     * 根据字段ID查询关联字段元数据
     */
    @GetMapping("/field/{fieldId}")
    public R<RelationMetaVo> getRelationFieldByFieldId(@PathVariable String fieldId) {
        return relationMetaService.findByFieldId(fieldId)
                .map(relation -> R.ok(BeanMapperUtils.map(relation, RelationMetaVo.class)))
                .orElse(R.fail("关联字段不存在"));
    }

    /**
     * 根据表ID查询所有关联字段元数据
     */
    @GetMapping("/table/{tableId}")
    public R<List<RelationMetaVo>> getRelationFieldsByTableId(@PathVariable String tableId) {
        List<RelationMeta> relationFields = relationMetaService.findAllByTableId(tableId);
        return R.ok(BeanMapperUtils.mapAsList(relationFields, RelationMetaVo.class));
    }

    /**
     * 创建关联字段元数据
     */
    @PostMapping
    public R<RelationMetaVo> createRelationField(@RequestBody RelationMetaDto relationMetaDto) {
        try {
            RelationMeta createdField = relationMetaService.createRelationMeta(relationMetaDto, SecurityUtils.getUserId());
            return R.ok(BeanMapperUtils.map(createdField, RelationMetaVo.class));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新关联字段元数据
     */
    @PutMapping("/{id}")
    public R<RelationMetaVo> updateRelationField(
            @PathVariable String id,
            @RequestBody RelationMetaDto relationMetaDto) {
        try {
            RelationMeta updatedField = relationMetaService.updateRelationMeta(id, relationMetaDto, SecurityUtils.getUserId());
            return R.ok(BeanMapperUtils.map(updatedField, RelationMetaVo.class));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除关联字段元数据
     */
    @DeleteMapping("/{id}")
    public R<Void> deleteRelationField(@PathVariable String id) {
        try {
            relationMetaService.deleteRelationMeta(id, SecurityUtils.getUserId());
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 创建关联关系
     */
    @PostMapping("/{relationFieldId}/relations")
    public R<Void> createRelation(
            @PathVariable String relationFieldId,
            @RequestParam String sourceRecordId,
            @RequestParam String targetRecordId) {
        try {
            relationMetaService.createRelation(relationFieldId, sourceRecordId, targetRecordId, SecurityUtils.getUserId());
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 批量创建关联关系
     */
    @PostMapping("/{relationFieldId}/relations/batch")
    public R<Void> createRelations(
            @PathVariable String relationFieldId,
            @RequestParam String sourceRecordId,
            @RequestBody List<String> targetRecordIds) {
        try {
            relationMetaService.createRelations(relationFieldId, sourceRecordId, targetRecordIds, SecurityUtils.getUserId());
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除关联关系
     */
    @DeleteMapping("/{relationFieldId}/relations")
    public R<Void> deleteRelation(
            @PathVariable String relationFieldId,
            @RequestParam String sourceRecordId,
            @RequestParam String targetRecordId) {
        try {
            relationMetaService.deleteRelation(relationFieldId, sourceRecordId, targetRecordId);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除源记录的所有关联关系
     */
    @DeleteMapping("/{relationFieldId}/relations/all")
    public R<Void> deleteAllRelations(
            @PathVariable String relationFieldId,
            @RequestParam String sourceRecordId) {
        try {
            relationMetaService.deleteAllRelations(relationFieldId, sourceRecordId);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取关联记录ID列表
     */
    @GetMapping("/{relationFieldId}/related-records")
    public R<List<String>> getRelatedRecordIds(
            @PathVariable String relationFieldId,
            @RequestParam String sourceRecordId) {
        try {
            List<String> relatedIds = relationMetaService.getRelatedRecordIds(relationFieldId, sourceRecordId);
            return R.ok(relatedIds);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 批量获取关联记录ID
     */
    @PostMapping("/{relationFieldId}/related-records/batch")
    public R<Map<String, List<String>>> getRelatedRecordsMap(
            @PathVariable String relationFieldId,
            @RequestBody List<String> sourceRecordIds) {
        try {
            Map<String, List<String>> relatedIdsMap = relationMetaService.getRelatedRecordsMap(
                    relationFieldId, sourceRecordIds);
            return R.ok(relatedIdsMap);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}